package server

import (
	"fmt"
	"net/http"
	"pointclient/config"
	"pointclient/datasource"
	"sync"
	"time"
)

var GHttpClient *http.Client
var once sync.Once

func CreateHttpClient() (*http.Client, bool) {
	var cli *http.Client
	var ret bool
	once.Do(func() {
		cli = &http.Client{
			Timeout: 5 * time.Second,
		}
		ret = true
	})
	return cli, ret
}

func InitServer() bool {
	// 初始化http客户端
	var ok bool
	GHttpClient, ok = CreateHttpClient()
	if !ok {
		return false
	}

	// 工厂配置初始化
	statusUrl := "http://" + config.GConfig.Point.ServerAddress + config.GConfig.Point.PointStatusUrl
	delayUrl := "http://" + config.GConfig.Point.ServerAddress + config.GConfig.Point.PointDelayUrl
	loginUrl := "http://" + config.GConfig.Point.ServerAddress + config.GConfig.Point.PointLoginUrl
	intreval := config.GConfig.Point.StatusInterval
	ok = datasource.GPointFactory.SetConfig(datasource.PointConfig{
		GHttpClient,
		statusUrl,
		delayUrl,
		loginUrl,
		intreval,
	})
	if !ok {
		return false
	}


	// 创建状态收集器
	statCollector, ok := datasource.GPointFactory.CreateCollector(datasource.PointStatus)
	if !ok {
		return false
	}
	fmt.Printf("[server] create %s success\n", datasource.PointStatus)
	// 创建时延收集器
	delayCollector, ok := datasource.GPointFactory.CreateCollector(datasource.PointDelay)
	if !ok {
		return false
	}
	fmt.Printf("[server] create %s success\n", datasource.PointDelay)

	// 注册
	datasource.GPointFactory.RegPointServer(datasource.PointStatus, statCollector)
	datasource.GPointFactory.RegPointServer(datasource.PointDelay, delayCollector)

	return true
}

func StartServer() bool {
	// 登录服务
	go func() {
		for {
			if ok := datasource.PointLogin(); !ok {
				fmt.Printf("[server] point login failed\n")
			} else {
				fmt.Printf("[server] point login susccess , token : %s\n", datasource.GLoginRsp.Token)
			}
			time.Sleep(time.Duration(config.GConfig.Point.LoginInterval) * time.Second)
		}
	}()

	// 启动状态收集器
	if ok, w := datasource.GPointFactory.GetPointServer(datasource.PointStatus); !ok {
		return false
	} else {
		go w.Work()
	}

	// 启动时延收集器
	if ok, w := datasource.GPointFactory.GetPointServer(datasource.PointDelay); !ok {
		return false
	} else {
		go w.Work()
	}

	return true
}